#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_DEGREE 10

typedef int Polynomial[MAX_DEGREE+1];

static void set_constant(Polynomial p, int k)
{
    int i;
    for (i = 1; i <= MAX_DEGREE; i++)
        p[i] = 0;
    p[0] = k;
}

static void mul_constant(Polynomial p, int k)
{
    int i;
    for (i = 0; i <= MAX_DEGREE; i++)
        p[i] *= k;
}

static void mul_variable(Polynomial p)
{
    int i;
    for (i = MAX_DEGREE; i > 0; i--)
        p[i] = p[i-1];
    p[i] = 0;
}

static void add_polynomial(Polynomial dst, const Polynomial src)
{
    int i;
    for (i = 0; i <= MAX_DEGREE; i++)
        dst[i] += src[i];
}

static void print_polynomial(const Polynomial p, char x)
{
    int i, nonzero = 0;
    for (i = MAX_DEGREE; i > 0; i--)
    {
        if (p[i] == 0)
            continue;
        if (nonzero > 0 && p[i] > 0)
            printf("+");
        if (p[i] != 1)
            printf("%d*", p[i]);
        printf("%c", x);
        if (i > 1)
            printf("^%d", i);
        nonzero++;
    }
    if (nonzero == 0)
        printf("%d", p[0]);
    else if (p[i] != 0)
        printf("%+d", p[0]);    
}

static void parse_op_statement(Polynomial runtime);
static void parse_loop_statement(Polynomial runtime);
static void parse_statement_list(Polynomial runtime);

static void parse_op_statement(Polynomial runtime)
{
    int k;
    scanf("%d", &k);
    set_constant(runtime, k);
}

static void parse_loop_statement(Polynomial runtime)
{
    char counter[50];
    scanf("%s", counter);

    parse_statement_list(runtime);

    if (counter[0] == 'n') /* LOOP n */
    {
        mul_variable(runtime);
    }
    else
    {
        int k = strtol(counter, NULL, 10);
        mul_constant(runtime, k);
    }
}

static void parse_statement_list(Polynomial runtime)
{
    set_constant(runtime, 0);
    while (1)
    {
        Polynomial one;
        char keyword[10];

        scanf("%s", keyword);
        if (strcmp(keyword, "LOOP") == 0)
            parse_loop_statement(one);
        else if (strcmp(keyword, "OP") == 0)
            parse_op_statement(one);
        else /* should be "END" */
            break;

        add_polynomial(runtime, one);
    }
}

static void parse_program(Polynomial runtime)
{
    scanf(" BEGIN");
    parse_statement_list(runtime);
}

int main()
{
    int n, i;
    scanf("%d", &n);
    for (i = 1; i <= n; i++)
    {
        Polynomial runtime;
        parse_program(runtime);
        printf("Program #%d\n", i);
        printf("Runtime = ");
        print_polynomial(runtime, 'n');
        printf("\n\n");
    }
    return 0;
}